import { setToken, removeToken, getToken, setTokenTime } from '../../utils/auth'
import { loginApi, getInfoApi, getUserInfoApi } from '../../api/user'

const state = {
  token: getToken(),
  // 用户个人性息
  userInfo: {}
}

const mutations = {
  SET_TOKEN (state, token) {
    state.token = token
    setToken(token)
  },
  REMOVE_TOKEN (state) {
    state.token = null
    removeToken()
  },
  // 给userinfo赋值的方法
  SET_USERINFO (state, paload) {
    state.userInfo = paload
  },
  // 删除userinfo的方法
  REMOVE_USERINFO (state) {
    state.userInfo = {}
  }
}

const actions = {
  login (context, data) {
    return new Promise((resolve, reject) => {
      loginApi(data)
        .then(res => {
          context.commit('SET_TOKEN', res)
          setTokenTime()
          resolve()
          console.log(res)
        })
        .catch(() => {
          reject()
        })
    })
  },
  // 调用接口，得到用户信息保存起来
  async getuserinfo (context) {
    const res = await getInfoApi()
    const result = await getUserInfoApi(res.userId)
    const data = { ...res, ...result }
    context.commit('SET_USERINFO', data)
    return data
  },
  logout ({ commit }) {
    commit('REMOVE_USERINFO')
    commit('REMOVE_TOKEN')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
